﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using CsvHelperPlus;

namespace DataSource
{
    public class LoadCsvFromDFW: ILoadData
    {
        private string lv2Path;
        private string tickPath;
        private string date;
        private DateTime st;
        private DateTime et;
        private string[] chgNum = { "一", "二", "三", "四", "五" };
        public LoadCsvFromDFW(string date)
        {
            tickPath = @"U:\data\tick\DFW";
            lv2Path = @"U:\data\level2\DFW";
            st = DateTime.ParseExact(date + "093000", "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
            et = DateTime.ParseExact(date + "150000", "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
            this.date = date;
        }

        public List<Level2Struct> LoadLv2(string code)
        {
            List<Level2Struct> lls = new List<Level2Struct>();
            string se = "";
            if (code[0] == '6')
            {
                se = "sh";
            }
            else
            {
                se = "sz";
            }
            string filePath = String.Format(@"{0}\{1}\{2}\{3}_{1}.csv", lv2Path,date,se,code);
            if (!File.Exists(filePath))
            {
                return null;
            }
            StreamReader sr = new StreamReader(filePath, Encoding.Default);
            string[] items = null;
            Dictionary<string, int> colmaps = new Dictionary<string, int>();
            string line;
            bool isColumn = true;

            while (!sr.EndOfStream)
            {
                line = sr.ReadLine();
                items = line.Split(',');
                if (isColumn)
                {
                    for(int i=0; i<items.Length; i++)
                    {
                        colmaps[items[i]] = i;
                    }
                    isColumn = false;
                    continue;
                }
                Level2Struct ls = new Level2Struct();
                ls.amount = double.Parse(items[colmaps["成交量"]]);
                ls.balance = double.Parse(items[colmaps["成交额"]]);
                ls.code = items[colmaps["证券代码"]];
                ls.price = float.Parse(items[colmaps["最新"]]);
                try{
                    ls.time = DateTime.ParseExact(items[colmaps["时间"]], "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
                }
                catch(System.FormatException){
                    ls.time = DateTime.Parse(items[colmaps["时间"]]);
                }
                

                for (int i = 1; i < 6; i++)
                {
                    ls.buy_px.Add(float.Parse(items[colmaps["买" + chgNum[i-1] +"价"]]));
                    ls.buy_amount.Add(int.Parse(items[colmaps["买" + chgNum[i - 1] + "量"]])*100);
                    ls.sell_px.Add(float.Parse(items[colmaps["卖" + chgNum[i - 1] + "价"]]));
                    ls.sell_amount.Add(int.Parse(items[colmaps["卖" + chgNum[i - 1] + "量"]])*100);
                }
               lls.Add(ls);
            }
            return lls;
        }

        public bool IsTheMarketTime(DateTime dt)
        {
            if ((dt >= st) && (dt <= et))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        
        public List<Level2Struct> LoadMarketLv2(List<string> stkList)
        {
            List<Level2Struct> lv2List = new List<Level2Struct>(1000000);
            foreach (var tk in stkList)
            {
                Console.WriteLine(tk);
                List<Level2Struct> lls = LoadLv2(tk);
                if(lls!=null) lv2List.AddRange(lls);
            }
            return lv2List.OrderBy(t => t.time).ToList(); //按时间排序
        }
        
        public List<TickStruct> LoadTick(string code)
        {
            List<TickStruct> lts = new List<TickStruct>();
            string prefix = "";
            if (code[0] == '6')
            {
                prefix = "SH";
            }
            else
            {
                prefix = "SZ";
            }
            string filePath = tickPath + "\\" + date + "\\" + prefix + code + ".csv";
            if (!File.Exists(filePath))
            {
                return null;
            }
            StreamReader sr = new StreamReader(filePath, Encoding.Default);
            string[] items = null;
            Dictionary<string, int> colmaps = new Dictionary<string, int>();
            string line;
            bool isColumn = true;
            while (!sr.EndOfStream)
            {
                line = sr.ReadLine();
                items = line.Split(',');
                if (isColumn)
                {
                    for (int i = 0; i < items.Length; i++)
                    {
                        colmaps[items[i]] = i;
                    }
                    isColumn = false;
                    continue;
                }
                TickStruct ts = new TickStruct();
                ts.code = code;
                ts.direction = items[colmaps["Direction"]];

                ts.price = float.Parse(items[colmaps["Price"]]);
                ts.volume = int.Parse(items[colmaps["Volume"]]);
                string time = items[colmaps["Time"]].PadLeft(6, '0');
                string mtime = items[colmaps["Mtime"]].PadLeft(3, '0');
                ts.time = DateTime.ParseExact(time+mtime, "yyyyMMddHHmmssfff", System.Globalization.CultureInfo.CurrentCulture);
                lts.Add(ts);
            }
            return lts;
        }

        public List<TickStruct> LoadMarketTick(List<string> stkList)
        {
            List<TickStruct> tickList = new List<TickStruct>(15000000);
            foreach (var tk in stkList)
            {
                Console.WriteLine(tk);
                List<TickStruct> lts = LoadTick(tk);
                if (lts != null) tickList.AddRange(lts);
            }
            return tickList.OrderBy(t => t.time).ToList(); //按时间排序
        }
    }
}
